import 'package:app_info/info/appsflyer.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:smartloan_mdc/extension/extension.dart';
import 'package:smartloan_mdc/http/api/api.dart';
import 'package:smartloan_mdc/pages/auth/base_auth.dart';
import 'package:smartloan_mdc/pages/widgets/app_btn.dart';
import 'package:smartloan_mdc/pages/widgets/text_input.dart';
import 'package:smartloan_mdc/res/string.dart';
import 'package:smartloan_mdc/res/theme.dart';
import 'package:smartloan_mdc/utils/auth/auth.dart';
import 'package:smartloan_mdc/utils/loading/loading.dart';
import 'package:smartloan_mdc/utils/locator/app_config.dart';
import 'package:smartloan_mdc/utils/locator/locator.dart';
import 'package:sml_policies/ui/agreement_view_dialog.dart';
import 'package:sml_policies/ui/permissions_dialog.dart';

import '../../route/app_routes.dart';

class PhonePage extends BaseAuth {
  const PhonePage({super.key});

  @override
  BaseAuthState<BaseAuth> getBaseAuthState() => _PhonePageState();
}

class _PhonePageState extends BaseAuthState<PhonePage> {

  @override
  String get pageName => 'loginphone';

  TextEditingController phoneCtrl = TextEditingController();
  int phoneLength = locator<AppConfig>().getAppConfig().phoneLength ?? 10;
  String phonePrefix = locator<AppConfig>().getAppConfig().phonePrefix ?? "";
  bool startWithPrefix = false;
  bool existed = false;
  bool enableAutoLogin = false;
  FocusNode focusNode = FocusNode();

  @override
  void initState() {
    AppsFlyer().logEvent('loginphone_open');

    Future.delayed(const Duration(milliseconds: 500), () async {
      await const PermissionsDialog().show(context);
      await AgreementViewDialog().show(context);
      focusNode.requestFocus();
    });

    super.initState();
  }

  @override
  Widget buildContent() {
    return Column(
      children: [
        20.h.hSizedBox(),
        phoneInput(),
        applyBtn(),
      ],
    );
  }

  Widget phoneInput() {
    return Row(
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        locator<AppConfig>().getAppConfig().areaCode.toString().sText(),
        10.w.wSizedBox(),
        Expanded(
          child: AppTextInput(
            // autofocus: true,
            controller: phoneCtrl,
            hintText: AppStr.phoneInputHint,
            focusNode: focusNode,
            inputFormatter: [
              startWithPrefix ? LengthLimitingTextInputFormatter(phoneLength + phonePrefix.length)
                : LengthLimitingTextInputFormatter(phoneLength),
              FilteringTextInputFormatter.digitsOnly
            ],
            keyboardType: TextInputType.phone,
            onChange: (value) {
              setState(() {
                startWithPrefix = value.toString().startsWith(phonePrefix);
              });
            },
          ).paddingOnly(bottom: 3.h)
        )
      ],
    ).decorationBox(
      color: AppTheme.inputBg,
      radius: 50.r,
      padding: EdgeInsets.symmetric(horizontal: 15.w, vertical: 12.h),
      margin: EdgeInsets.symmetric(horizontal: 15.w, vertical: 20.h)
    );
  }

  Widget applyBtn() {
    return AppBtn(
      content: AppStr.apply,
      onTap: apply,
    ).marginSymmetric(
      horizontal: 15.w
    );
  }

  void apply() async {
    AppsFlyer().logEvent('loginphone_next');

    if (phoneCheck()) {
      try {
        showLoading();

        Map res = await RequestApi.existsByMobile(phoneFormat(phoneCtrl.text)) as Map;
        existed = res['existed'];

        Map smsRes = await RequestApi.getSmsCode(phoneFormat(phoneCtrl.text), existed ? 1 : 2) as Map;
        enableAutoLogin = smsRes['enableAutoLogin'];

        if (enableAutoLogin) {
          AppsFlyer().logEvent(existed ? 'login_automatic' : 'login_autoreg');
          try {
            Map authRes = await RequestApi.userAuth(phoneFormat(phoneCtrl.text), smsRes['code'] ?? '', isLogin: existed, verified: !enableAutoLogin) as Map;
            AppsFlyer().logEvent(existed ? 'login_automatic_success' : 'login_autoreg_success');
            Auth.login(authRes);
            Get.toNamed(AppRoutes.home, arguments: {
              'url': locator<AppConfig>().appConfigModel.baseUrl,
              'checkVersion': true
            });

          } on Exception catch (e) {
            AppsFlyer().logEvent(existed ? 'login_automatic_fail' : 'login_autoreg_fail');
          }

        } else {
          Get.toNamed(AppRoutes.code, arguments: {'phone': phoneFormat(phoneCtrl.text), 'existed': existed});
        }

      } on Exception catch (e) {
        // AppHttpBaseConfig().exceptionHandle(e);
      } finally {
        hideLoading();
      }

    }
  }

  bool phoneCheck() {
    if (!getAgree) {
      AppStr.termCheck.toast(pageName: pageName);
      return false;
    }

    if (phoneCtrl.text.isEmpty) {
      AppStr.phoneEmpty.toast(pageName: pageName);
      return false;
    }

    // 输入长度检测
    if (phoneCtrl.text.length !=
      (phoneCtrl.text.startsWith(phonePrefix)
        ? (phoneLength + phonePrefix.length)
        : phoneLength)
    ) {
      AppStr.phoneIncorrect.toast(pageName: pageName);
      return false;
    }

    return true;
  }

  String phoneFormat(String phoneNumber) {
    if (phoneNumber.startsWith(phonePrefix)) {
      phoneNumber = phoneNumber.replaceFirst(phonePrefix, '');
    }
    return phoneNumber;
  }



}
